/*
用户登录
 */
function userLogin() {
    let email = loginForm.email.value;
    let password = loginForm.password.value;
    doLogin(email, password);
}

/**
 * @function 用户登录
 * @param email 登录邮箱
 * @param password 登录密码
 */
function doLogin(email, password) {
    let loginUrl = "/chaos/api/auth/login";
    $.ajax({
        url: loginUrl,
        method: "post",
        data: JSON.stringify({
            "email": email,
            "password": password
        }),
        contentType: "application/json",
        dataType: "json",
        success: function (res) {
            if (res.code === 1000) {
                sessionStorage.setItem("token", res.body);
                window.location.href = "../chaos/index.html";
                // window.location.href = "../chaos/play.html";
            } else {
                layer.msg(res.message);
            }
        },
        error: function (err) {
            layer.alert("登录失败");
        }
    });
}

function userLogout() {
    let logoutUrl = "/chaos/api/play/logout";
    $.ajax({
        async: false,
        method: 'post',
        headers: {
            'token': getLoginToken()
        },
        url: logoutUrl,
        success: function (res) {
            window.location.href = "./login.html";
        }
    });
}

/*
用户注册
 */
function userRegister() {
    let email = registerForm.email.value;
    let registerCode = registerForm.registerCode.value;
    let nickName = registerForm.nickName.value;
    let password = registerForm.password.value;
    doRegister(email, registerCode, nickName, password);
}


/**
 * @function 进行用户注册
 * @param email 注册的邮箱
 * @param registerCode 注册验证码
 * @param nickName 注册的昵称
 * @param password 注册的密码
 */
function doRegister(email, registerCode, nickName, password) {
    let registerUrl = "/chaos/api/auth/register";
    $.ajax({
        url: registerUrl,
        method: "post",
        data: JSON.stringify({
            "email": email,
            "registerCode": registerCode,
            "nickName": nickName,
            "password": password
        }),
        contentType: "application/json",
        dataType: "json",
        success: function (res) {
            if (res.code === 1000) {
                layer.msg(res.body.nickName + "，您已成功注册，请重新登录", {
                    icon: 1,
                    time: 1000
                }, function () {
                    window.location.href = "../chaos/login.html";
                });
            } else {
                layer.msg(res.message);
            }
        },
        error: function (err) {
            alert("注册失败");
        }
    });
}

/**
 * 重置密码
 */
function resetPsd() {
    let email = resetPsdForm.email.value;
    let resetPsdCode = resetPsdForm.resetPsdCode.value;
    let password = resetPsdForm.password.value;
    doResetPsd(email, resetPsdCode, password);
}


/**
 * @function 重置密码
 * @param email 用户邮箱
 * @param resetPsdCode 重置验证码
 * @param password 新的密码
 */
function doResetPsd(email, resetPsdCode, password) {
    let resetPsdUrl = "/chaos/api/auth/reset-psd";
    $.ajax({
        url: resetPsdUrl,
        method: "post",
        data: JSON.stringify({
            "email": email,
            "resetPsdCode": resetPsdCode,
            "password": password
        }),
        contentType: "application/json",
        dataType: "json",
        success: function (res) {
            if (res.code === 1000) {
                layer.msg(res.body.nickName + "，您已成功重置密码，请重新登录", {
                    icon: 1,
                    time: 1000
                }, function () {
                    window.location.href = "../chaos/login.html";
                });
            } else {
                layer.msg(res.message);
            }
        },
        error: function (err) {
            alert("重置密码失败");
        }
    });
}

/**
 * 修改信息
 */
function changeInfo() {
    let nickName = changeInfoForm.nickName.value;
    doChangeInfo(nickName);
}


/**
 * @function 修改信息
 * @param nickName 新的昵称
 */
function doChangeInfo(nickName) {
    let changeInfoUrl = "/chaos/api/play/change-info";
    $.ajax({
        url: changeInfoUrl,
        method: "post",
        headers: {
            'token': getLoginToken()
        },
        data: JSON.stringify({
            "nickName": nickName
        }),
        contentType: "application/json",
        dataType: "json",
        success: function (res) {
            if (res.code === 1000) {
                layer.msg(res.body.nickName + "，您已成功修改信息，正在自动跳转到首页", {
                    icon: 1,
                    time: 1000
                }, function () {
                    window.location.href = "../chaos/index.html";
                });
            } else {
                layer.msg(res.message);
            }
        },
        error: function (err) {
            alert("修改信息失败");
        }
    });
}

/**
 * @function 发送注册验证码
 */
function sendRegisterCode() {
    let sendRegisterCode = $("#sendRegisterCode");
    sendRegisterCode.html("正在发送...");
    sendRegisterCode.removeAttr("onclick");
    let registerCodeUrl = "/chaos/api/auth/register-code/" + registerForm.email.value;
    $.ajax({
        url: registerCodeUrl,
        method: "get",
        contentType: "application/json",
        dataType: "json",
        success: function (res) {
            if (res.code === 1000 || res.code === 1001) {
                if (res.code === 1000) {
                    layer.msg("验证码发送成功");
                } else {
                    layer.msg("已经发送过邮件了，请查看您的邮箱，或者稍后重试~~~~");
                }
                let releaseTime = res.body;
                countDown();

                function countDown() {
                    if (releaseTime === 0) {
                        sendRegisterCode.html("发送验证码");
                        sendRegisterCode.attr("onclick", "sendRegisterCode()")
                        return;
                    } else {
                        sendRegisterCode.removeAttr("onclick");
                        sendRegisterCode.html("重新发送(" + releaseTime + ")")
                        releaseTime--;
                    }
                    setTimeout(countDown, 1000);
                }
            } else {
                layer.msg(res.message);
                sendRegisterCode.html("发送验证码");
                sendRegisterCode.attr("onclick", "sendRegisterCode()")
            }

        },
        error: function (err) {
            layer.msg("验证码发送失败");
            sendRegisterCode.html("发送验证码");
            sendRegisterCode.attr("onclick", "sendRegisterCode()")
        }
    });
}


/**
 * @function 发送重置密码验证码
 */
function sendResetPsdCode() {
    let sendResetPsdCode = $("#sendResetPsdCode");
    sendResetPsdCode.html("正在发送...");
    sendResetPsdCode.removeAttr("onclick");
    let resetPsdCodeUrl = "/chaos/api/auth/reset-psd-code/" + resetPsdForm.email.value;
    $.ajax({
        url: resetPsdCodeUrl,
        method: "get",
        contentType: "application/json",
        dataType: "json",
        success: function (res) {
            if (res.code === 1000 || res.code === 1001) {
                if (res.code === 1000) {
                    layer.msg("验证码发送成功");
                } else {
                    layer.msg("已经发送过邮件了，请查看您的邮箱，或者稍后重试~~~~");
                }
                let releaseTime = res.body;
                countDown();

                function countDown() {
                    if (releaseTime === 0) {
                        sendResetPsdCode.html("发送验证码");
                        sendResetPsdCode.attr("onclick", "sendResetPsdCode()")
                        return;
                    } else {
                        sendResetPsdCode.removeAttr("onclick");
                        sendResetPsdCode.html("重新发送(" + releaseTime + ")")
                        releaseTime--;
                    }
                    setTimeout(countDown, 1000);
                }
            } else {
                layer.msg(res.message);
                sendResetPsdCode.html("发送验证码");
                sendResetPsdCode.attr("onclick", "sendResetPsdCode()")
            }

        },
        error: function (err) {
            layer.msg("验证码发送失败");
            sendResetPsdCode.html("发送验证码");
            sendResetPsdCode.attr("onclick", "sendResetPsdCode()")
        }
    });
}

function getLoginToken() {
    let token = sessionStorage.getItem("token");
    return token;
}

/**
 * 确保用户登录了，没有登录则跳转到登录页面
 * @param res
 */
function ensureLogin(res) {
    if (res.code === 4001) {
        layer.msg(res.message, {
            time: 2000
        }, function () {
            window.location.href = "../chaos/login.html";
        });
    }
}

/**
 * 获取当前登录用户信息，并更新到页面
 */
function getUserInfo() {
    let getUserInfoUrl = "/chaos/api/play/user-info";
    $.ajax({
        method: 'get',
        headers: {
            'token': getLoginToken()
        },
        url: getUserInfoUrl,
        success: function (res) {
            ensureLogin(res);
            let userNickNames = document.getElementsByClassName("user-nick-name");
            for (let i = 0; i < userNickNames.length; i++) {
                let userNickNameTag = userNickNames[i];
                userNickNameTag.innerHTML = res.body.nickName + '<i class="layui-icon layui-icon-down layui-nav-more"></i>';
            }
            sessionStorage.setItem("userInfo", JSON.stringify(res.body));
        }
    });
}

/**
 * 获取当前登录用户的ID, 没有登录的话会返回0
 * @returns {number|*}
 */
function getUserId() {
    try {
        return JSON.parse(sessionStorage.getItem("userInfo")).id;
    } catch (e) {
        console.error(e);
    }
    return 0;
}